package org.karelun.rabbit.rcp.ui.handler;

import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.net4j.CDONet4jSession;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.cdo.view.CDOView;
import org.karelun.rabbit.graph.Diagram;
import org.karelun.rabbit.graph.GraphFactory;


public class OpenEMFEditorHandler extends OpenEMFViewHandler {
	
	@Override
	protected CDOView openCDOView(CDONet4jSession session) {
		return session.openTransaction();
	}
	
	@Override
	protected boolean hasResource(CDOView cdoView, String resourcePathName) {
		boolean hasResource = super.hasResource(cdoView, resourcePathName);
		if(hasResource){
			return true;
		}
		CDOTransaction transaction=(CDOTransaction)cdoView;
		createResource(transaction, resourcePathName);
		return super.hasResource(cdoView, resourcePathName);
	}
	
	private void createResource(CDOTransaction transaction,String resourcePathName){
		CDOResource resource = transaction.createResource(resourcePathName);
		Diagram diagram = GraphFactory.eINSTANCE.createDiagram();
		resource.getContents().add(diagram);
		try {
			transaction.commit();
		} catch (CommitException e) {
			e.printStackTrace();
		}
	}
	
//	@Override
//	protected void openEditor(IWorkbenchPage page, CDOView cdoView) {
//		CDOTransaction transaction=(CDOTransaction)cdoView;
//		String resourcePath = getResourcePathName();
//		if(!transaction.hasResource(resourcePath)){
//			CDOResource resource = transaction.createResource(resourcePath);
//			Diagram diagram = GraphFactory.eINSTANCE.createDiagram();
//			resource.getContents().add(diagram);
//			try {
//				transaction.commit();
//			} catch (CommitException e) {
//				e.printStackTrace();
//			}
//		}
//		try {
//			//Fill the resource into transaction's resource set.
//			String path = transaction.getResource(resourcePath).getPath();
//			RabbitEditorInput editorInput = new RabbitEditorInput(cdoView, path);
//			page.openEditor(editorInput, "org.karelun.emf.rabbit.editor");
//		 } catch (PartInitException e) {
//			 e.printStackTrace();
//		 }
//	}
}
